package com.itboye.lottery.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.itboye.bylibrary.util.TimeUtils;
import com.itboye.bylibrary.widget.glide.GlideUtil;
import com.itboye.lottery.R;
import com.itboye.lottery.bean.FollowIndexBean;
import com.itboye.lottery.fragment.gendan.GendanCaseJine;
import com.itboye.lottery.view.rounded.RoundedImageView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by wu on 2018/1/9.
 */

public class GenDanCaseJinEAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    ArrayList<FollowIndexBean.ListEntity> classEntityArrayList = new ArrayList<>();
    Fragment fragment;

    public GenDanCaseJinEAdapter(Fragment fragment, ArrayList<FollowIndexBean.ListEntity> classEntityArrayList) {
        this.classEntityArrayList = classEntityArrayList;
        this.fragment = fragment;
    }

    public OnItemClickListener itemClickListener;

    public void setOnItemClickListener(GenDanCaseJinEAdapter.OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }


    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        return new ViewHolderCaseJinE(LayoutInflater.from(context).inflate(R.layout.item_gendan_case_money, parent, false));
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ViewHolderCaseJinE viewHolderCaseJinE = (ViewHolderCaseJinE) holder;
        viewHolderCaseJinE.ll_table.removeAllViews();
        FollowIndexBean.ListEntity listEntity = classEntityArrayList.get(position);
        viewHolderCaseJinE.tv_follow.setTag(position);
        viewHolderCaseJinE.tv_follow.setTag(R.id.tag_1, 1);
        viewHolderCaseJinE.tv_follow.setOnClickListener((GendanCaseJine) fragment);
        caculateFollowMoney(viewHolderCaseJinE.item_hotpeople_total_money, 1, position);
        GlideUtil.displayForCircle(context, listEntity.getHead_pic(), R.mipmap.head_default, viewHolderCaseJinE.iv_user_icon);
        viewHolderCaseJinE.tv_user_name.setText(listEntity.getNickname());
        if (listEntity.getRed_num() <= 0) {
            viewHolderCaseJinE.tv_lianhong.setVisibility(View.GONE);
        } else {
            viewHolderCaseJinE.tv_lianhong.setVisibility(View.VISIBLE);
            viewHolderCaseJinE.tv_lianhong.setText(listEntity.getRed_num() + "连红");
        }
        viewHolderCaseJinE.iv_user_icon.setTag(R.id.tag_1, listEntity.getUser_id());
        viewHolderCaseJinE.iv_user_icon.setOnClickListener((GendanCaseJine) fragment);
        viewHolderCaseJinE.item_follow_end_time.setText("截止时间:" + TimeUtils.getFormatTime(listEntity.getEnd_time() * 1000, "MM-dd HH:mm"));//截止时间
        ((TextView) viewHolderCaseJinE.tb_row_1.getChildAt(0)).setText(listEntity.getTotal_amount() + "元");//认购金额
        ((TextView) viewHolderCaseJinE.tb_row_1.getChildAt(1)).setText(listEntity.getFollow_num() + "人");//跟单人数
        ((TextView) viewHolderCaseJinE.tb_row_1.getChildAt(2)).setText(listEntity.getCount_amount() + "元");//跟单金额
        String[] freePass = listEntity.getFree_pass().split(",");
        StringBuffer stringBuffer = new StringBuffer();
        for (String pass : freePass) {
            if (pass.contains("*")) {
                stringBuffer.append(pass.replace("*", "串"));
            } else {
                stringBuffer.append(pass + "串1");
            }
            stringBuffer.append(",");
        }
        if (stringBuffer.toString().endsWith(",")) {
            stringBuffer = new StringBuffer(stringBuffer.substring(0, stringBuffer.length() - 1));
        }
        int public_type = Integer.parseInt(listEntity.getPublic_type());
        String plan = listEntity.getOrigin_num();//投注内容
        int lotteryType = listEntity.getLottery_type();//跟单类型 2：篮球 1：足球
        JSONObject jsonObject = null;
//        listEntity.getPublic_type()
        try {
            if (!TextUtils.isEmpty(plan)) {
                jsonObject = new JSONObject(plan);
                if (listEntity.getBall_info() != null) {
                    HashMap<String, String> hashMap = new HashMap<>();
                    Log.v("bet_params", listEntity.getBall_info().size() + "  size:" + position);
                    for (int i = 0; i < listEntity.getBall_info().size(); i++) {
                        View view = View.inflate(context, R.layout.item_row, null);
                        TableRow tablerow_content = view.findViewById(R.id.tablerow_content);
                        FollowIndexBean.ListEntity.BallInfoEntity ballInfoEntity = listEntity.getBall_info().get(i);
                        String bDate = ballInfoEntity.getB_date().replaceAll("-", "");
                        String num = ballInfoEntity.getNum_type();
                        JSONObject jsonObject1 = jsonObject.getJSONObject(bDate + num);
                        Iterator<String> iterator = jsonObject1.keys();
                        while (iterator.hasNext()) {
                            StringBuffer stringBufferValue = new StringBuffer();
                            String key = iterator.next();
                            hashMap.put(key, key);
                            System.out.println("bet_type  ==" + key + "   hash_map.size==" + hashMap.size() + "  position==" + position);
                            JSONObject jsonObjectValue = jsonObject1.getJSONObject(key);
                            Iterator<String> iterator2 = jsonObjectValue.keys();
                            // 3010: 胜平负
                            // 3006:让球胜平负
                            // 3007: 全场比分(90分钟)
                            // 3008: 进球数
                            // 3009: 半全场胜负

                            // 3001: 非让分胜负
                            // 3002: 让分
                            // 3002: 胜负差
                            // 3004: 大小分
                            // 3011: 混合过关 （一注投注中包含2个玩法以上的就是混合过关）
                            switch (key) {
                                case "3010":
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        if (key2.equals("0")) {
                                            stringBufferValue.append("主负,");
                                        }
                                        if (key2.equals("1")) {
                                            stringBufferValue.append("主平,");
                                        }
                                        if (key2.equals("3")) {
                                            stringBufferValue.append("主胜,");
                                        }
                                    }
                                    break;
                                case "3007": //让球胜平负
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        if (!key2.equals("single")) {
                                            JSONObject value = jsonObjectValue.getJSONObject(key2);//种类所带表的赔率
                                            Iterator<String> iterator3 = value.keys();
                                            while (iterator3.hasNext()) {
                                                String key3 = iterator3.next();
                                                stringBufferValue.append(key3.substring(0, 1) + ":" + key3.substring(1, 2) + ",");
                                            }
                                        }
                                    }
                                    break;
                                case "3006":
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        if (!key2.equals("single")) {
                                            if (key2.equals("0")) {
                                                stringBufferValue.append("让负,");
                                            }
                                            if (key2.equals("1")) {
                                                stringBufferValue.append("让平,");
                                            }
                                            if (key2.equals("3")) {
                                                stringBufferValue.append("让胜,");
                                            }
                                        }
                                    }
                                    break;
                                case "3008":
                                    //总进球
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        if (key2.equals("goals")) {
                                            try {
                                                JSONObject jsonObject2 = jsonObjectValue.getJSONObject(key2);
                                                Iterator<String> iterator1 = jsonObject2.keys();
                                                while (iterator1.hasNext()) {
                                                    String key3 = iterator1.next();
                                                    stringBufferValue.append(key3 + "球,");
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }

                                        }
                                    }
                                    break;
                                case "3009":
                                    //半全场
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        if (!key2.equals("single")) {
                                            stringBufferValue.append(key2.replaceAll("3", "胜").replaceAll("1", "平").replaceAll("0", "负") + ",");
                                        }
                                    }
                                    break;
                                //-------------------------篮球相关---------------
                                case "3001"://胜负
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        String sfValue = "";
                                        if (key2.equals("0")) {
                                            sfValue = "让客胜";
                                        }
                                        if (key2.equals("3")) {
                                            sfValue = "让主胜";
                                        }
                                        if (!TextUtils.isEmpty(sfValue)) {
                                            stringBufferValue.append(sfValue);
                                            stringBufferValue.append(",");
                                        }
                                    }
                                    break;
                                case "3002"://让胜负
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        String rsfValue = "";
                                        if (key2.equals("0")) {
                                            rsfValue = "客胜";
                                        }
                                        if (key2.equals("3")) {
                                            rsfValue = "主胜";
                                        }
                                        if (!TextUtils.isEmpty(rsfValue)) {
                                            stringBufferValue.append(rsfValue);
                                            stringBufferValue.append(",");
                                        }
                                    }
                                    break;
                                case "3003": //胜负差
                                    boolean hasAdLHead = false, hasAdWHead = false;
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        String sfcValue = "";
                                        if (key2.startsWith("l")) {
                                            if (!hasAdLHead) {
                                                hasAdLHead = true;
                                                sfcValue = "客胜";
                                                stringBufferValue.append("客胜");
                                            }
                                            if (key2.equals("l1")) {
                                                sfcValue = "[1-5]";
                                            }
                                            if (key2.equals("l2")) {
                                                sfcValue = "[6-10]";
                                            }
                                            if (key2.equals("l3")) {
                                                sfcValue = "[11-15]";
                                            }
                                            if (key2.equals("l4")) {
                                                sfcValue = "[16-20]";
                                            }
                                            if (key2.equals("l5")) {
                                                sfcValue = "[21-25]";
                                            }
                                            if (key2.equals("l6")) {
                                                sfcValue = "[26+]";
                                            }
                                        } else if (key2.startsWith("w")) {
                                            if (!hasAdWHead) {
                                                hasAdWHead = true;
                                                stringBufferValue.append("主胜");
                                                sfcValue = "主胜";
                                            }
                                            if (key2.equals("w1")) {
                                                sfcValue = "[1-5]";
                                            }
                                            if (key2.equals("w2")) {
                                                sfcValue = "[6-10]";
                                            }
                                            if (key2.equals("w3")) {

                                                sfcValue = "[11-15]";
                                            }
                                            if (key2.equals("w4")) {

                                                sfcValue = "[16-20]";
                                            }
                                            if (key2.equals("w5")) {
                                                sfcValue = "[21-25]";
                                            }
                                            if (key2.equals("w6")) {
                                                sfcValue = "[26+]";
                                            }
                                        }

                                        if (!TextUtils.isEmpty(sfcValue)) {
                                            stringBufferValue.append(sfcValue);
                                            stringBufferValue.append(",");
                                        }
                                    }
                                    break;
                                case "3004":
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        String dxfValue = "";
                                        if (key2.equals("0")) {
                                            dxfValue = "小分";
                                        }
                                        if (key2.equals("1")) {
                                            dxfValue = "大分";
                                        }
//                                        //预设总分
//                                        if (key2.equals("score")) {
//                                            stringBufferValue.append("预设分(" + value + ")<br />");
//                                        }
                                        if (!TextUtils.isEmpty(dxfValue)) {
                                            stringBufferValue.append(dxfValue);
                                            stringBufferValue.append(",");
                                        }
                                    }
                                    break;
                            }
                            ((TextView) tablerow_content.getChildAt(3)).setText((stringBufferValue.toString().endsWith(",") ? (stringBufferValue.toString().substring(0, stringBufferValue.length() - 1)) : stringBufferValue));
                        }

                        ((TextView) tablerow_content.getChildAt(0)).setText(ballInfoEntity.getNum());
                        ((TextView) tablerow_content.getChildAt(1)).setText(ballInfoEntity.getH_cn());
                        ((TextView) tablerow_content.getChildAt(2)).setText(ballInfoEntity.getA_cn());
                        viewHolderCaseJinE.ll_table.addView(view, viewHolderCaseJinE.ll_table.getChildCount() - 1);
                    }
                    if (hashMap.size() > 1) {//混合
                        if (lotteryType == 2) {
                            viewHolderCaseJinE.tv_lottery_type.setText("篮球混合投注");
                        } else {
                            viewHolderCaseJinE.tv_lottery_type.setText("足球混合投注");
                        }
                    } else if (hashMap.size() == 1) {//单种投注
                        if (hashMap.containsKey("3010")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("胜平负");
                        } else if (hashMap.containsKey("3006")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("让球胜平负");

                        } else if (hashMap.containsKey("3007")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("全场比分");

                        } else if (hashMap.containsKey("3008")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("进球数");

                        } else if (hashMap.containsKey("3009")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("半场胜平负");

                        } else if (hashMap.containsKey("3011")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("足球混合投注");
                        } else if (hashMap.containsKey("3001")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("让分胜负");
                        } else if (hashMap.containsKey("3002")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("非让分胜负");
                        } else if (hashMap.containsKey("3003")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("胜负差");

                        } else if (hashMap.containsKey("3004")) {
                            viewHolderCaseJinE.tv_lottery_type.setText("大小分");

                        }
//                                viewHolderCaseJinE.tv_lottery_type.setText("足球混合投注");
                    }
//                    }
//                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean isSecret = !(public_type == 2);
        if (isSecret) {
            viewHolderCaseJinE.tablerow_secret.setVisibility(View.VISIBLE);
            viewHolderCaseJinE.ll_table.setVisibility(View.GONE);
            viewHolderCaseJinE.tablerow_title.setVisibility(View.GONE);
            viewHolderCaseJinE.rl_head.setVisibility(View.GONE);
        } else {
            viewHolderCaseJinE.tablerow_secret.setVisibility(View.GONE);
            viewHolderCaseJinE.ll_table.setVisibility(View.VISIBLE);
            viewHolderCaseJinE.tablerow_title.setVisibility(View.VISIBLE);
            viewHolderCaseJinE.rl_head.setVisibility(View.VISIBLE);
            if (stringBuffer.equals("1串1")) {
                stringBuffer = new StringBuffer("单关");
            }
            viewHolderCaseJinE.tv_pass_type.setText(stringBuffer);
        }
        viewHolderCaseJinE.item_follow_iv_type.setBackgroundResource(lotteryType == 2 ? R.mipmap.lanqiu : R.mipmap.zuqiu);
//        ((ViewHolderFind) holder).title.setText(hash.getImg_url());
//        ((ViewHolderFind) holder).content.setText(content);
//        ((ViewHolderFind) holder).icon.setBackgroundResource(hash.getClassification_name());
//        GlideUtil.display(context, list.get(position).getImg_url(), holder.img);
//        holder.name.setText(list.get(position).getClassification_name());
        viewHolderCaseJinE.tv_group_buy_des.setOnClickListener(view -> showInputDialog((TextView) view, viewHolderCaseJinE.item_hotpeople_total_money, viewHolderCaseJinE.tv_follow, position));
    }

    @Override
    public int getItemCount() {
        return classEntityArrayList == null ? 0 : classEntityArrayList.size();
    }

    public class ViewHolderCaseJinE extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView title, tv_user_name, item_follow_end_time;
        public TextView content, tv_follow, tv_pass_type, tv_lottery_type, tv_secret;
        TableRow tablerow_secret, tablerow_title, tb_row_1;
        RoundedImageView iv_user_icon;
        TableLayout ll_table;
        TextView tv_lianhong;
        RelativeLayout rl_head;
        TextView tv_group_buy_des, item_hotpeople_total_money;
        ImageView item_follow_iv_type;

        public ViewHolderCaseJinE(View itemView) {
            super(itemView);
            iv_user_icon = itemView.findViewById(R.id.iv_user_icon);
            tv_user_name = itemView.findViewById(R.id.tv_user_name);
            item_follow_end_time = itemView.findViewById(R.id.item_follow_end_time);
            tablerow_secret = itemView.findViewById(R.id.tablerow_secret);
//            tablerow_content = itemView.findViewById(R.id.tablerow_content);
            tablerow_title = itemView.findViewById(R.id.tablerow_title);
            tb_row_1 = itemView.findViewById(R.id.tb_row_1);
            tv_follow = itemView.findViewById(R.id.tv_follow);
            tv_pass_type = itemView.findViewById(R.id.tv_pass_type);
            tv_lottery_type = itemView.findViewById(R.id.tv_lottery_type);
            ll_table = itemView.findViewById(R.id.ll_table);
            tv_secret = itemView.findViewById(R.id.tv_secret);
            tv_lianhong = itemView.findViewById(R.id.tv_lianhong);
            rl_head = itemView.findViewById(R.id.rl_head);
            tv_group_buy_des = itemView.findViewById(R.id.tv_group_buy_des);
            item_hotpeople_total_money = itemView.findViewById(R.id.item_hotpeople_total_money);
            item_follow_iv_type = itemView.findViewById(R.id.item_follow_iv_type);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (itemClickListener != null) {
                itemClickListener.onItemClick(v, getAdapterPosition());
            }
        }
    }

    private void showInputDialog(final TextView ed, final TextView item_hotpeople_total_money, TextView textView, final int position) {
        AlertDialog.Builder alert = new AlertDialog.Builder(context);
        alert.setTitle("输入倍数");
        View view = View.inflate(context, R.layout.alert_x, null);
        final EditText editText = view.findViewById(R.id.edit_content);
        editText.setText(ed.getText());
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setHint("请输入倍数");
        alert.setView(view);
        alert.setPositiveButton("确认", (dialogInterface, i) -> {
            ed.setText(editText.getText());
            ed.setTag(editText.getText());
            textView.setTag(R.id.tag_1, Integer.parseInt(editText.getText().toString()));
            caculateFollowMoney(item_hotpeople_total_money, Integer.parseInt(editText.getText().toString()), position);
        });
        alert.setNegativeButton("取消", (dialogInterface, i) -> {

        });
        alert.create().show();
    }

    private void caculateFollowMoney(TextView textView, int multiple, int position) {
        textView.setText(multiple * Float.parseFloat(classEntityArrayList.get(position).getSingle_amount()) + "元");
    }

}
